package main

import (
	"crypto/md5"
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"encoding/hex"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

type LoginUser struct {
	Account  string `json:"account" form:"account" binding:"required"`
	Password string `json:"password" form:"password" binding:"required"`
}

func Login(c *gin.Context) {
	var u LoginUser
	// Bind user
	if err := c.ShouldBind(&u); err != nil {
		c.String(http.StatusBadRequest, "err:%v", err)
		log.Fatalln(err)
	}
	// If account exist return userid, else return 0
	var uid int
	var psw string
	err := db.QueryRow("SELECT id, password FROM goadmin_user WHERE account=? LIMIT 1", u.Account).Scan(
		&uid, &psw)
	if err != nil && err != sql.ErrNoRows {
		c.String(http.StatusBadGateway, "Something wrong with db, err:%v", err)
		log.Fatalln(err)
	}
	if uid > 0 {
		encryptCode := parsemd5(u.Password)
		if encryptCode == psw {
			c.JSON(http.StatusOK, gin.H{
				"status": 10200,
				"msg":    "login success",
				"userid": uid,
			})
			return
		}
	}
	if uid == 0 {
		c.JSON(http.StatusOK, gin.H{
			"status": 10300,
			"msg":    "need register",
			"userid": 0,
		})
		return
	}
	c.String(http.StatusBadGateway, "Server error with wrong userid:%v", uid)
}

type RegistUser struct {
	Account  string `json:"account" form:"account" binding:"required"`
	Password string `json:"password" form:"password" binding:"required"`
	Phone    string `json:"phone" form:"phone" binding:"required"`
	EMail    string `json:"email" form:"email" binding:"required"`
}

func Register(c *gin.Context) {
	var u RegistUser
	// Bind user
	if err := c.ShouldBind(&u); err != nil {
		c.String(http.StatusBadRequest, "%v", err)
		log.Fatalln(err)
	}
	// Check if account exist
	var uid int
	err := db.QueryRow("SELECT id FROM goadmin_user WHERE account=? LIMIT 1", u.Account).Scan(&uid)
	if err != nil {
		c.String(http.StatusBadGateway, "DB query err:%v", err)
		log.Fatalln(err)
	}
	if uid > 0 {
		c.JSON(http.StatusOK, gin.H{
			"status": 10500,
			"msg":    "account used",
		})
		return
	}
	// Create user
	encryptCode := parsemd5(u.Password)
	stmt, err := db.Prepare(`INSERT INTO goadmin_user(account, password, phone, email) VALUES (?,?,?,?)`)
	if err != nil {
		c.String(http.StatusBadGateway, "DB insert err:%v", err)
		log.Fatalln(err)
	}
	rs, err := stmt.Exec(u.Account, encryptCode, u.Phone, u.EMail)
	if err != nil {
		c.String(http.StatusBadGateway, "DB insert err:%v", err)
		log.Fatalln(err)
	}
	stmt.Close()
	id, err := rs.LastInsertId()
	if err != nil {
		c.String(http.StatusBadGateway, "DB insert err:%v", err)
		log.Fatalln(err)
	}
	c.JSON(http.StatusOK, gin.H{
		"status": 10200,
		"msg":    "regist success",
		"userid": id,
	})
}

func parsemd5(str string) string {
	h := md5.New()
	h.Write([]byte(str))
	return hex.EncodeToString(h.Sum(nil))
}
